# @author  : 沈海
# @time    : 2021/10/12 0012 17:36
# @function: the script is used to do something.
# @version : 
#   V1 
# -*-coding:utf-8-*-
import json

from home.models import Article,ArticleCategory


def common_data(request):
    # 获取所有分类信息数据1
    articleCategories = ArticleCategory.objects.all()

    # 接受用户点击的分类id
    cat_id = request.GET.get('cat_id', 1)

    # 根据分类id进行分类的查询
    try:
        select_articleCategory = ArticleCategory.objects.get(id=cat_id)
    except ArticleCategory.DoesNotExist:
        select_articleCategory = ArticleCategory.objects.get(id=1)

    # 根据被选中的文章分类显示他下的所有
    article = Article.objects.filter(category=select_articleCategory)


    # 最新文章
    news_art = Article.objects.order_by('-create_time')[0:2]

    # 重新查询文章信息。按照浏览量降序排序
    hot_tags = Article.objects.order_by('-total_views').distinct()[:9]

    if request.COOKIES.get("login_name") is not None:
        username = json.loads(request.COOKIES.get("login_name"))
    else:
        username = ""

    return {
        "newArt": news_art,
        "hotTags": hot_tags,
        "articleCategories": articleCategories,
        "select_articleCategory": select_articleCategory,
        "username": username
    }
